﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace GetEmailAttachment
{
    class SearchResult
    {
        /// <summary>
        /// 邮件实例
        /// </summary>
        private MailMessage m_MailMsg;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mm">邮件实例参数</param>
        public SearchResult(MailMessage mm)
        {
            m_MailMsg = mm;
        }

        /// <summary>
        /// 是否选中
        /// </summary>
        public bool Selected
        {
            get;
            set;
        }

        /// <summary>
        /// 邮件主题
        /// </summary>
        public string Subject
        {
            get
            {
                return m_MailMsg?.Subject?.ToString();
            }
        }

        /// <summary>
        /// 邮件发件人
        /// </summary>
        public string From
        {
            get
            {
                return m_MailMsg?.From?.ToString();
            }
        }

        /// <summary>
        /// 邮件附件数
        /// </summary>
        public int? AttachmentsCount
        {
            get
            {
                return m_MailMsg?.Attachments?.Count();
            }
        }

        /// <summary>
        /// 下载附件至指定文件夹
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="act">委托方法</param>
        public void DownLoadAttachments(string path, Action act = null)
        {
            HasError = false;
            if (m_MailMsg != null && m_MailMsg.Attachments.Count() > 0)
            {
                string logpath = "log.txt";
                FileHelper.CreateFile(logpath,false);
                string dateStr = DateTime.Now.ToString("yyyyMMdd");
                string subStr = string.IsNullOrEmpty(m_MailMsg.Subject) ? "空主题" : m_MailMsg.Subject;
                subStr = subStr.Replace("\\", "").Replace("/", "").Replace("?", "").Replace("？", "")
                    .Replace("*", "").Replace(":", "").Replace("：", "").Replace(">", "").Replace("<", "").Replace("|", "").Replace("\"", "")
                    .Replace("{","").Replace("｛", "").Replace("}", "").Replace("｝", "");
                subStr = subStr.Length > 50 ? subStr.Substring(0, 50) : subStr;
                string folder = path + (path.EndsWith("\\") ? "" : "\\") + dateStr + "\\" + subStr + "\\";
                try
                {
                    //创建目录
                    FileHelper.CreateFolder(folder);
                    m_MailMsg.Attachments.ToList().ForEach((a) =>
                    {
                        string name = a.Name;
                        //处理文件名没有转码
                        if (a.NameEncoding == null && a.TransferEncoding == System.Net.Mime.TransferEncoding.Base64)
                        {
                            try
                            {
                                //name = FileHelper.Decode("=?gb2312?B?ueO3orv5vfDI7bz+vLzK9bf+zvHIt8jPtaVfMjAxNzA3X0ZyZWVib3JkZXJz?= =?gb2312?Q?(IT)=5FV01.xlsx?=");
                                name = FileHelper.Decode(a.Name);
                                //name = FileHelper.Decode("=?gb2312?B?ueO3orv5vfDI7bz+vLzK9bf+zvHIt8jPtaVfMjAxODA1X1N5bWJpbyAoSVQp?= =?gb2312?Q?=5FV01.xlsx?=");
                            }
                            catch (Exception ex)
                            {
                                FileHelper.WriteLineToTxt(logpath, string.Format("error-文件名转码-{1}:{0}", ex.Message, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                            }
                        }
                        string filePath = "";
                        try
                        {
                            filePath = Path.Combine(folder, name);
                            FileHelper.CreateFile(filePath);
                            FileHelper.StreamToFile(a.ContentStream, filePath);
                            act?.Invoke();
                        }
                        catch (Exception ex)
                        {
                            FileHelper.WriteLineToTxt(logpath, $"error-文件下载-{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }:主题【{m_MailMsg.Subject}】附件【{m_MailMsg.Attachments.IndexOf(a)}】保存路径【{filePath}】{ex.Message}");
                            HasError = true;
                        }
                    });
                }
                catch (Exception ex)
                {
                    FileHelper.WriteLineToTxt(logpath, $"error-文件下载-{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }:主题【{m_MailMsg.Subject}】{ex.Message}");
                    HasError = true;
                }
            }
        }
        public bool HasError = false;
    }
}
